React 19에서 새롭게 도입된 use
API는 비동기 데이터를 더 쉽게 다룰 수 있도록 도와주는 훅입니다. 기존에는 useEffect + useState
를 조합해야 했지만, use
를 사용하면 더 간결한 코드로 데이터를 가져올 수 있고, Suspense와 자연스럽게 결합됩니다.
💡 주요 특징
- 비동기 데이터 처리 간소화:
useEffect
없이도 데이터를 가져올 수 있음- Suspense와의 자연스러운 결합: 로딩 상태를 자동으로 관리 가능
- 컨텍스트 값 조건부 읽기 지원: useContext보다 유연한 사용 가능
- React Server Components(RSC)에서 활용 가능
use
API 사용법import { use, Suspsense } from "react";
function Comments({ commentsPromise }) {
const comments = use(commentsPromise);
reuturn comments.map((comment) => <p key={commnent.id}>{comment}</p>)
}
function Page({ commentsPromise }) {
return (
<Suspense fallback={<div>Loading...</div>}>
<Comments commentsPromise={commentsPromise}> />
</Suspense>
)
}
✔️ use
를 사용하면 useEffect
없이도 데이터를 직접 가져올 수 있습니다.
✔️ Suspsen
와 함께 사용하면 로딩 상태를 자동으로 관리할 수 있습니다.
useEffect + useState
사용)import { useState, useEffect } from "react";
function Comments({ commentsPromise }) {
const [comments, setComments] = useState(null);
useEffect(() => {
commentsPromise.then(setComments);
}, [commentsPromise]);
if (!comments) {
return <div>Loading...</div>;
}
return comments.map((comment) => <p key={comment.id}>{comment}</p>);
}
✔️ useEffect
와 useState
를 사용해야 하고, 로딩 상태를 따로 관리해야 합니다.
use
API를 사용한 방식import { use, Suspense } from "react";
function Comments({ commentsPromise }) {
const comments = use(commentsPromise);
return comments.map((comment) => <p key={comment.id}>{comment}</p>);
}
✔️ use
를 사용하면 비동기 데이터가 자동으로 처리됩니다.
✔️ useState
와 useEffect
없이도 데이터를 가져올 수 있습니다.
use
활용use
는 컨텍스트 값을 조건부로 읽을 수 있도록 도와줍니다.
기존 useContext
는 항상 실행되지만, use
를 사용하면 특정 조건에서만 컨텍스트르 가져올 수 있습니다.
useContext
사용 방식import { useContext } from "react";
import ThemeContext from "./ThemeContext";
function Haeding({ children }) {
const theme = useContext(ThemeContext);
return <h1 style={{ color: theme.color }}>{children}</h1>;
}
✔️ 항상 컨텍스트 값을 가져오기 때문에, 조건부 렌더링이 어려움
use
API를 사용한 방식import { use } from "react";
import ThemeContext from "./ThemeContext";
function Heading({ children }) {
if (!children) return null;
const theme = use(ThemeContext);
return <h1 style={{ color: theme.color }}>{children}</h1>;
}
✔️ 특정 조건(if (!children) return null;)
에서만 컨텍스트를 가져올 수 있어 더 유연함
use
API 사용 시 주의할 점function Comments() {
const comments = use(fetchComments()); // ❌ 이렇게 하면 안 됨
return comments.map((comment) => <p key={comment.id}>{comment}</p>);
}
✔️ use
는 이미 생성된 프로미스만 사용 가능합니다.
✔️ 해결 방법: 프로미스를 미리 생성한 후 전달해야 합니다.
const commentsPromise = fetchComments();
function Comments() {
const comments = use(commentsPromise); // ✅ 미리 생성된 프로미스를 사용
return comments.map((comment) => <p key={comment.id}>{comment}</p>);
}
✔️ use
는 Suspense와 함께 사용해야 정상 동작합니다.
✔️ 서버 사이드 렌더링(SSR) 환경에서도 유용하게 활용 가능